package com.one.common.location_service;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.one.common.common.system.SystemModel;
import com.one.common.common.system.model.param.UploadGpsParam;
import com.one.common.common.system.model.response.DefaultResponse;
import com.one.common.common.system.model.response.OrderStateResponse;
import com.one.common.config.CMemoryData;
import com.one.common.config.CPersisData;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.receiver.NotificationHandle;
import com.one.common.utils.Logger;
import com.one.common.utils.StringUtils;
import com.one.common.utils.map.LocationUtils;

import androidx.annotation.Nullable;

import static com.one.common.config.MyContact.UPLOAD_LOCATION_TIME;
import static com.one.common.receiver.NotificationHandle.NOTIFICATION_ID;

/**
 * Created by tsj-004 on 2017/11/10.
 * <p>
 * 定时上传定位信息服务
 * fixed 固定
 * cycle 周期
 */

public class FixedCycleLocationService extends Service implements AMapLocationListener {
    private String TAG = "LocationService";
    AMapLocationClient mLocationClient = null;

    private boolean isShow = false;
    private final static int FOREGROUND_ID = 888;

    @Override
    public void onCreate() {
        super.onCreate();
        startDoLocation();  // 开始定位
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d(TAG);
        setNotification();
        return super.onStartCommand(intent, flags, startId);
    }

    private void setNotification() {
        if (!isShow && CPersisData.getIsLogin()) {
            Intent intentNotification = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("ycpcarapp://openpage?actionAndroid=com.ycp.car.main.ui.activity.MainActivity&param1=1"));
            intentNotification.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentPend = PendingIntent.getActivity(this, 0,
                    intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForeground(FOREGROUND_ID, new NotificationHandle(this).crate("您有订单在运输中",
                        "持续为您服务", intentPend));
            } else {
                new NotificationHandle(this).notify("您有订单在运输中",
                        "持续为您服务", intentPend);
            }
            isShow = true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isShow = false;
        closeNotify();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 开始定位
     */
    private void startDoLocation() {
        Logger.d(TAG, "开始定位  FixedCycleLocationService");
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = LocationUtils.getDefaultOption();
        option.setInterval(UPLOAD_LOCATION_TIME);
        option.setOnceLocation(false);
        option.setOnceLocationLatest(false);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(this);
        mLocationClient.startLocation();
    }

    /**
     * 定位回调
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Logger.d(TAG, "定位回调  FixedCycleLocationService  " + (aMapLocation != null));
        if (aMapLocation != null && aMapLocation.getLongitude() > 0 && aMapLocation.getLatitude() > 0) {
            Logger.d(TAG, "定位成功  FixedCycleLocationService");
            UploadGpsParam locationInfo = new UploadGpsParam(aMapLocation);
            // 在内存中存储定位信息
            CMemoryData.setLocationInfo(locationInfo);
            if (StringUtils.isNotBlank(CMemoryData.getUserMobile()) && CPersisData.getIsLogin()) {
                requestServer(locationInfo);
            } else {
                Logger.e(TAG, "用户未登录缺少请求头字段mobile");
            }
        }
    }

    /**
     * 车主上传定位信息
     */
    private void requestServer(final UploadGpsParam params) {
        Logger.d(TAG, params.toString());
        new SystemModel().uploadGps(params, new ObserverOnNextListener<DefaultResponse>() {
            @Override
            public void onNext(DefaultResponse object) {
                Logger.d(TAG, "上传定位信息至服务器成功  FixedCycleLocationService");
            }

            @Override
            public void onError(String errorCode, String msg) {
                Logger.e(TAG, "上传定位信息至服务器失败  FixedCycleLocationService");
            }
        });

        new SystemModel().getOrderState(new ObserverOnNextListener<OrderStateResponse>() {

            @Override
            public void onNext(OrderStateResponse orderStateResponse) {
                if (!orderStateResponse.getIs_transiting()) {
                    closeNotify();
                 } else {
                    setNotification();
                }
            }

            @Override
            public void onError(String errorCode, String msg) {
                setNotification();
            }
        });

    }

    @SuppressLint("WrongConstant")
    public void closeNotify() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(FOREGROUND_ID);
            stopForeground(true);
        } else {
            new NotificationHandle(FixedCycleLocationService.this)
                    .getManager().cancel(NOTIFICATION_ID);
        }
    }
}